package com.tgy.blog.interceptors;

import com.tgy.constant.RedisKey;
import com.tgy.core.service.BlogArticleService;
import com.tgy.pojo.BlogArticle;
import com.tgy.util.IPUtils;
import com.tgy.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 用于拦截每次刷新都会为文章增加阅读量
 *
 * 根据用户登录的ip进行判断的，在阅读文章时会根据文章ID和IP组合在redis中添加一条数据，数据内容就是IP,
 * 拦截到阅读增加阅读量方法的时候只需要将这个ID+IP再去redis中查询是否存在即可，存在则不增加阅读量，不存在则增加
 */
public class ArticleReadInterceptor implements HandlerInterceptor {

    @Autowired
    public RedisUtils redis;
    @Resource
    private BlogArticleService blogArticleService;

    /**
     * 拦截请求，访问controller之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断这个IP是否已经观看过文章
        String articleId = request.getParameter("articleId");
        // 判断文章存不存在，防止恶意传入文章ID导致redis中数据量增大
        BlogArticle article = blogArticleService.queryById(articleId);
        if (Objects.isNull(article)){
            return false;
        }
        String userIp = IPUtils.getRequestIp(request);
        userIp = userIp.replaceAll(":",".");
        boolean isExist = redis.keyIsExist(RedisKey.REDIS_ARTICLE_USER_WATCH + ":" +  articleId + ":" + userIp);
        return !isExist;
    }

    /**
     * 请求访问到controller之后，渲染视图之前
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求访问到controller之后，渲染视图之后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
